package array

import "math"

func myAtoi(s string) int {

	res := 0
	sign := 1

	if s == "" {
		return 0
	}

	start := 0
	for ; start < len(s) && s[start] == ' '; start++ {
	}

	if start < len(s) && s[start] == '-' {
		sign = -1
		start++
	} else if start < len(s) && s[start] == '+' {
		start++
	}

	for start < len(s) && s[start] >= '0' && s[start] <= '9' {
		res = res*10 + int(s[start]-'0')
		start++
		if res > math.MaxInt32 {
			break
		}
	}

	if sign == -1 {
		res = -res
	}

	if res >= math.MaxInt32 {
		return math.MaxInt32
	} else if res < -math.MaxInt32-1 {
		return -math.MaxInt32 - 1
	}

	return res

}
